

var baseConfig = function(axios) {
  return axios.defaults.baseURL = baseURL
}

var transformRequest = function(axios) {
  return axios.defaults.transformRequest = [
    function(data, headers) {
      if (data === undefined) {
        return
      }
      if (data.emulateFile) {
        delete data['emulateFile']
        headers['Content-Type'] = 'multipart/form-data;charset=UTF-8'
        return data.fileData
      }
      if (data.emulateJSON) {
        delete data['emulateJSON']
        headers['Content-Type'] = 'application/json;charset=UTF-8'
        return JSON.stringify(data)
      }
      if (data.emulateQS) {
        delete data['emulateQS']
        headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
        return Qs.stringify(data)
      }
      return data
    }
  ]
}

var addRequestInterceptors = function(axios) {
  return axios.interceptors.request.use(
    function(config) {
      return config
    },
    function(error) {
      return Promise.reject(error)
    }
  )
}

var addResponseInterceptors = function(axios) {
  return axios.interceptors.response.use(
    function(response) {
      return Promise.resolve(response)
    },
    function(error) {
      return Promise.reject(error)
    }
  )
}

var accessInVue = function(Vue, axios, name = '$http') {
  return Vue.prototype[name] = axios
}

var config = function(Vue, name) {
  baseConfig(axios)
  transformRequest(axios)
  addRequestInterceptors(axios)
  addResponseInterceptors(axios)
  accessInVue(Vue, axios, name)
}

var api = function(argsObj) {
  var url = argsObj.url,
      method = argsObj.method,
      params = argsObj.params,
      emulateJSON = argsObj.emulateJSON,
      emulateQS = argsObj.emulateQS,
      useAjaxBar = argsObj.useAjaxBar,
      useLoadLayer = argsObj.useLoadLayer,
      timeout = argsObj.timeout,
      successCallback = argsObj.successCallback,
      errorCallback = argsObj.errorCallback
  var reqConf = {
    method: method,
    url: url,
    useLoadLayer: useLoadLayer,
    useAjaxBar: useAjaxBar
  }
  // post 请求
  if (method === 'post' && emulateJSON) {
    params.emulateJSON = true;
  }
  if (method === 'post' && emulateQS) {
    params.emulateQS = true;
  }

  reqConf[method === 'post' ? 'data' : 'params'] = params;

  if (!timeout) {
    axios.defaults.timeout = 150000;
  }
  return axios(reqConf)
    .then(function(response) {
      var rspCode = response.data.success
      if (!!rspCode) {
        // 业务级成功
        if (successCallback) {
          return successCallback(response.data)
        }
      } else if(response.data.length>0) { // 处理无状态查询接口的返回
        if (successCallback) {
          return successCallback(response.data)
        }
      } else {
        // 业务级失败
        // 可以处理提示内容
        if (errorCallback) {
          return errorCallback(response.data)
        }
      }
    })
    .catch(function(error) {
      // 服务端异常
    })
  }

config(Vue, '$axios')
Vue.prototype.$api = api  